package com.whl.sm.service.impl.repair;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.repair.RepairApplyMapper;
import com.whl.sm.model.notice.Attachment;
import com.whl.sm.model.repair.RepairApply;
import com.whl.sm.model.repair.RepairTask;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.model.system.SysDict;
import com.whl.sm.service.notice.AttachmentService;
import com.whl.sm.service.repair.DataOperateLogService;
import com.whl.sm.service.repair.RepairApplyService;
import com.whl.sm.service.repair.RepairTaskService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.service.system.SysDictService;
import com.whl.sm.sysEnum.CommonEnum;
import com.whl.sm.vo.WxRepairApplyTaskVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-11-28
 */
@Slf4j
@Service
public class RepairApplyServiceImpl extends ServiceImpl<RepairApplyMapper, RepairApply> implements RepairApplyService {

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private DataOperateLogService dataOperateLogService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Lazy
    @Autowired
    private RepairTaskService repairTaskService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private AttachmentService attachmentService;


    @Override
    public Result getDetailById(String applyId) {
        try {
            RepairApply applyData = getBaseMapper().selectById(applyId);
            RepairTask taskData = null;
            OrgUserInfo applicant = orgUserInfoService.getByUserId(applyData.getApplicant());
            applyData.setApplicantName(applicant==null?null:applicant.getUserName());
            OrgUserInfo operator = orgUserInfoService.getByUserId(applyData.getOperator());
            applyData.setOperatorName(operator==null?null:operator.getUserName());
            SysDict repairType = sysDictService.getById(applyData.getRepairType());
            applyData.setRepairTypeName(repairType==null?null:repairType.getDictValue());
            List<Attachment> applyImgLIst = attachmentService.getByDataId(applyData.getId());
            if (applyImgLIst.size() > 0) {
                applyData.setApplyImgList(applyImgLIst.stream().map(Attachment::getFile).collect(Collectors.toList()));
            }
            if (applyData.getStep()>=CommonEnum.RepairStatus.DISTRIBUTION.getStep()){
                List<RepairTask> taskList =  repairTaskService.list(new QueryWrapper<RepairTask>().eq("link_apply_id",applyData.getId()));
                taskData = taskList.size()>0?taskList.get(0):null;
                if (Objects.nonNull(taskData)){
                    OrgUserInfo staff = orgUserInfoService.getByUserId(taskData.getStaffId());
                    taskData.setStaffName(staff!=null?staff.getUserName():"");
                }
            }
            WxRepairApplyTaskVo rtValue = new WxRepairApplyTaskVo(applyData,taskData);
            return Result.ok(rtValue);
        }catch (Exception e){
            log.error("获取报修详细信息异常=========>"+e.getMessage());
            return Result.fail();
        }
    }

    @Override
    public Result update(RepairApply repairApply) {
        try{
            repairApply.setOperator(orgUserService.getCurrentUserId());
            String currentStatus = CommonEnum.RepairStatus.getValueByStep(repairApply.getStep());
            if (Objects.isNull(repairApply.getRepairStatus()) || !currentStatus.equals(repairApply.getRepairStatus())){
                repairApply.setRepairStatus(currentStatus);
                Result addLog = dataOperateLogService.addOperateLog(repairApply.getId(),"REPAIR_APPLY",currentStatus+"--->"+repairApply.getOpinionRemark());
                if (!addLog.isOk()){
                    return addLog;
                }
            }
            if (Objects.isNull(repairApply.getId())){
                getBaseMapper().insert(repairApply);
            }else {
                getBaseMapper().updateById(repairApply);
            }
        }catch (Exception e){
            log.error("报修申请更新异常:"+e.getMessage());
            return Result.fail();
        }
        return Result.ok(repairApply.getId());
    }


    @Override
    public Result dispatchTask(String staffId, String linkApplyId) {
        try {
            RepairApply originApply = getById(linkApplyId);
            originApply.setStep(CommonEnum.RepairStatus.DISTRIBUTION.getStep());
            //更新申请单
            Result updateResult = update(originApply);
            if (!updateResult.isOk()){
                return updateResult;
            }
            //生成维修工单
            OrgUserInfo linkService = orgUserInfoService.getByUserId(staffId);
            RepairTask insertTask = new RepairTask();
            insertTask.setStaffId(staffId);
            insertTask.setLinkApplyId(linkApplyId);
            insertTask.setStaffTel(linkService.getLinkTel());
            insertTask.setOperator(orgUserService.getCurrentUserId());
            insertTask.setRepairFeedback("工单分派");
            Result insertResult = repairTaskService.update(insertTask);
            if (!insertResult.isOk()){
                return insertResult;
            }

        }catch (Exception e){
            log.error("报修派单操作失败:"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }


}
